package org.bot.server.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.bot.client.driver.api.client.ClientOpenApi;
import org.bot.server.client.mapper.BotClientMapper;
import org.bot.server.client.entity.BotClient;
import org.bot.server.client.service.BotClientService;
import org.bot.server.flow.entity.BotFlow;
import org.bot.server.flow.mapper.BotFlowMapper;
import org.bot.server.job.FlowQuartzJob;
import org.bot.server.utils.AESUtils;
import org.bot.server.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 沧月
 * @create 0020 2023/9/20 09:48
 * @description <description class purpose>
 */
@Service
public class BotClientServiceImpl implements BotClientService {


    @Autowired
    BotClientMapper botClientMapper;

    @Autowired
    FlowQuartzJob quartzJob;

    @Autowired
    BotFlowMapper flowMapper;


    @Autowired
    ClientOpenApi clientOpenApi;


    @Value("${bot.ws-host}")
    String botHost;

    @Override
    public List<BotClient> getBotClientList(int page, int size, String name) {
        List<BotClient> list = botClientMapper.list(name, (page - 1) * size, size);
        list.forEach(b -> {
            b.setSecret(truncateAndReplace(b.getSecret()));
        });
        return list;
    }

    @Override
    public int getBotClientListCount(String name) {
        return botClientMapper.listCount(name);
    }

    @Override
    public boolean save(String clientName) {
        BotClient botClient = new BotClient();
        botClient.setName(clientName);
        botClient.setClientId(UUID.randomUUID().toString());
        botClient.setSecret(UUID.randomUUID().toString());
        botClient.setStatus(1);
        return botClientMapper.insert(botClient) > 0;
    }

    @Override
    public boolean delete(int id) {
        //检查改客户端是否有流程
        QueryWrapper<BotFlow> wrapper = new QueryWrapper<>();
        wrapper.eq("client_id", id);
        List<Map<String, Object>> list = flowMapper.selectMaps(wrapper);
        if (!list.isEmpty()) {
            return false;
        }

        //清除该前置机的定时任务
        BotClient botClient = botClientMapper.selectById(id);
        quartzJob.deleteClientJob(botClient.getClientId());

        return botClientMapper.deleteById(id) > 0;
    }

    private String truncateAndReplace(String input) {
        if (input == null || input.length() <= 8) {
            return input;
        }

        int startIndex = 0;
        int endIndex = input.length() - 5;
        return input.substring(startIndex, 3) +
                "**********" +
                input.substring(endIndex);
    }

    @Override
    public boolean edit(String clientName, int id) {
        BotClient botClient = new BotClient();
        botClient.setId(id);
        botClient.setName(clientName);
        return botClientMapper.updateById(botClient) > 0;
    }

    @Override
    public boolean disable(String clientId, Integer status) {
        BotClient botClient = new BotClient();
        botClient.setStatus(status);
        UpdateWrapper<BotClient> wrapper = new UpdateWrapper<>();
        wrapper.eq("client_id", clientId);

        boolean stat = botClientMapper.update(botClient, wrapper) > 0;
        if (stat) {
            if (status == 2) {
                quartzJob.addClientJob(clientId);
            } else {
                quartzJob.deleteClientJob(clientId);
            }
        }
        return stat;
    }


    @Override
    public void downCertificate(HttpServletResponse response, String id) {
        String secret = UUID.randomUUID().toString();
        String code = UUID.randomUUID().toString().replaceAll("-", "");

        //更新前置机密钥
        BotClient client = new BotClient();
        client.setId(Integer.parseInt(id));
        client.setSecret(secret);
        client.setActivateCode(code);
        client.setActivateStatus(0);
        botClientMapper.updateById(client);

        //生成密钥信息
        BotClient botClient = botClientMapper.selectById(id);
        JSONObject cerData = new JSONObject();
        cerData.fluentPut("secret", secret)
                .fluentPut("clientId", botClient.getClientId())
                .fluentPut("status", false)
                .fluentPut("url", botHost);
        ServletUtils.downEncryptionFile(response, code, cerData, "bot-client-certificate.cer");
    }

    @Override
    public boolean interruptAllTask(String clientId) {
        return clientOpenApi.interrupt(clientId);
    }
}
